package cqrtplm.aop;


import com.hustcad.plm.caddoc.service.impl.batchimport.TyplmCADBatchImportUtil;
import com.hustcad.plm.middle.caddocapi.service.TyplmDwgFileParseService;
import com.hustcad.plm.pdm.caddoc.model.dto.ImportXmlDTO;
import com.hustcad.plm.pdm.enumeration.model.vo.ItemValueVO;
import com.hustcad.plm.pdm.enumeration.service.TyplmEnumerationService;
import com.hustcad.plm.pdm.middle.caddoc.model.dto.Import2dDocForTsDTO;
import com.hustcad.plm.pdm.middle.caddoc.model.dto.Import2dDocForWebDTO;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.entity.cad.CADDocDO;
import cqrtplm.constant.RTErrorCodeEnum;
import cqrtplm.mapper.StoragePlanningMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author fxw
 * @version 1.0
 * @ClassName RTImportDwgAOP
 * @Description TODO
 * @since 2025/11/4 20:55
 */
@Aspect
@Component
@Slf4j
public class RTImportDwgAOP {
    /**
     * 已生效不能在导入对应数据了
     */
    private final static String RELEASED = "已生效";
    /**
     * 已经创建数据
     */
    private final static String CREATING = "创建中";
    /**
     * 已经创建数据
     */
    private final static String UNDERCHANGE = "变更中";

    @Resource
    private StoragePlanningMapper storagePlanningMapper;
    @Resource
    private TyplmEnumerationService typlmEnumerationService;
    @Resource
    private TyplmDwgFileParseService typlmDwgFileParseService;
    @Resource
    private TyplmCADBatchImportUtil typlmCADBatchImportUtil;

    @Around("execution(* com.hustcad.plm.middle.caddocapi.controller.TyplmImportDwgController.importCadFileFromWeb(..))")
    public Object importDwgAOP(ProceedingJoinPoint pjp) throws Throwable {
        Object[] args = pjp.getArgs();
        if (args == null) {
            return pjp.proceed();
        }

        Object arg = args[0];
        if (!(arg instanceof Import2dDocForTsDTO)) {
            return pjp.proceed();
        }


        //解析获取xml图纸信息
        Import2dDocForTsDTO import2dDocForTsDTO = (Import2dDocForTsDTO) arg;
        if (ObjectUtils.isEmpty(import2dDocForTsDTO.getFile())) {
            throw RTErrorCodeEnum.DOC_TYPE_ERROR.getException(
                    String.format("文件异常请重新上传图片"));
        }
        Import2dDocForWebDTO import2dDocForWebDTO = new Import2dDocForWebDTO();
        BeanUtils.copyProperties(import2dDocForTsDTO, import2dDocForWebDTO);

        if (!"Capital".equals(import2dDocForWebDTO.getSoftware())) {
            import2dDocForWebDTO.setNotAnalysisPartCode(import2dDocForWebDTO.getNotAnalysisCode());
            import2dDocForWebDTO.setNotAnalysisPartName(import2dDocForWebDTO.getNotAnalysisName());
        }
        String standXmlStr = null;
        ImportXmlDTO importXmlDTO = null;
        try {
            standXmlStr = typlmDwgFileParseService.dwgFileParse(import2dDocForWebDTO);
            importXmlDTO= typlmCADBatchImportUtil.xml2Object(standXmlStr);
        } catch (Exception e) {
            log.error(e.getMessage());
            pjp.proceed();
        }

        //获取xml信息
        if (ObjectUtils.isEmpty(importXmlDTO) || ObjectUtils.isEmpty(importXmlDTO.getDocList())) {
            throw RTErrorCodeEnum.DOC_TYPE_ERROR.getException(
                    String.format("参数异常%s", import2dDocForWebDTO.getNotAnalysisName()));
        }

        String docName = importXmlDTO.getDocList().get(0).getDlgGuid();

        if (docName != null && !docName.isEmpty()) {
            // 逗号或空格分隔
            String[] parts = docName.split("[,\\s]+");
            List<CADDocDO> resultEntityVOList = storagePlanningMapper.queryCadByNumberAndVersion(parts[0]);
            List<ItemValueVO> lifeCycleStateByType = typlmEnumerationService.getLifeCycleStateByType(
                    TableTypeConstrant.TY_CADDOC_OTYPE);

            Map<String, String> collect = lifeCycleStateByType.stream().collect(
                    Collectors.toMap(ItemValueVO::getCode, ItemValueVO::getName));

            for (CADDocDO resultEntityVO : resultEntityVOList) {

                String lifecycleStageKey = resultEntityVO.getLifecyclestagekey();
                String lifecycleStageName = collect.get(lifecycleStageKey);

                if (RELEASED.equals(lifecycleStageName)) {
                    throw RTErrorCodeEnum.DOC_TYPE_ERROR.getException(
                            String.format("图纸 %s 状态为%s,不允许更新", resultEntityVO.getName(), lifecycleStageName));
                }

                if (!(CREATING.equals(lifecycleStageName) || UNDERCHANGE.equals(lifecycleStageName))) {
                    throw RTErrorCodeEnum.DOC_TYPE_ERROR.getException(
                            String.format("图纸 %s 状态为%s,不允许更新", resultEntityVO.getName(), lifecycleStageName));
                }

                if ("c/o".equals(resultEntityVO.getLockstateinfo())) {
                    throw RTErrorCodeEnum.DOC_TYPE_ERROR.getException(
                            String.format("图纸%s已检出,不允许更新", resultEntityVO.getName()));
                }
            }
        }
        log.info("结束导入DWG文件:{}", import2dDocForTsDTO.getDocName());

        return pjp.proceed();
    }
}
